<template>
  <div class="v-editor-select-rows g-flex g-ov-hidden">
    <div class="g-flex-1">
      <MDropdown :disabled="row.readonly || isModelDisabled">
        <div class="g-jc-sb g-pd-l-8 g-pointer">
          <div class="g-flex-1">
            {{ localValue }}
          </div>
          <div
            v-if="selected && !row.readonly && !isModelDisabled"
            class="g-flex-0 g-pd-lr-4"
          >
            <img src="statics/icons/app/iconlist2.png" />
          </div>
        </div>
        <template #dropdown>
          <MDropdownMenuItem
            v-for="item in options"
            :key="item.value"
            class="g-one-line"
            @click="handleClickItem(item)"
          >
            {{ item.label }}
          </MDropdownMenuItem>
        </template>
      </MDropdown>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { PropertyRow, PropertyDropdownOption } from "../../types";
import { modelService } from "@/modules/model/service";
import { ref, watch, inject, Ref } from "vue";
import { propertyUtil } from "../../PropertyUtil";
import { BusEvent } from "@/constants/Enums";
import MDropdown from "@/common/dropdown/Dropdown.vue";
import MDropdownMenuItem from "@/common/dropdown/DropdownMenuItem.vue";
import { reliabilitySelectOptionsMap } from "./ValueSpecificationTypes";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
}>();

const localValue = ref(props.row.value as string);
const options = reliabilitySelectOptionsMap.get(props.row.key) || [];

const saveValue = async (item: PropertyDropdownOption) => {
  if (item.value === localValue.value) {
    return;
  }
  const dto = propertyUtil.getUpdatePropertyDtoByPropertyRow(props.row, app.activeProject!.id);
  dto.value = item.value;
  localValue.value = item.value;
  let res = await modelService.updateModelProperty(dto);

  if (res) {
    app.$bus.emit(BusEvent.REFRESH_POPERTY, props.row.modelId);
  }
};

watch(
  () => props.row.value,
  () => {
    localValue.value = props.row.value as string;
  }
);

function handleClickItem(item: PropertyDropdownOption) {
  saveValue(item);
}
</script>
<style lang="scss" scoped>
.v-editor-select-rows {
  display: flex;
  .c-dropdown {
    border-bottom: 1px solid #ddd;
    &:last-of-type {
      border-bottom: 0;
    }
  }
  ._input-rows-operation-btns {
    border-left: 1px solid #ddd;
  }
}

._current-row {
  .v-editor-select-rows {
    .c-dropdown {
      &:last-of-type {
        border-bottom: 1px solid #ddd;
      }
    }
  }
}
</style>
